package com.sina.common.util;

import android.app.Activity;
import android.content.Context;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DataUtils {

    public static String formatDate(long aLong) {
        return formatDate(aLong,"yyyy-MM-dd HH:mm:ss");
    }

    public static String formatDate(long aLong,String format) {
        SimpleDateFormat sfd = new SimpleDateFormat(format, Locale.CHINA);
        Date date_format = new Date(aLong);
        return sfd.format(date_format);
    }

    public static String objectToString(Object object) {
        return new Gson().toJson(object);
    }

    public static void saveStringToData(Context context, String inputText, String fileName) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String loadDataToString(Activity activity, String fileName) {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = activity.openFileInput(fileName);//文件名
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

    public static void updateFile(final String uploadUrl, final String uploadFilePath, final String[] key, final String[] value, final String tag, final UpdateListener updateListener) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (updateListener != null) {
                    updateListener.onStart();
                }

                String end = "\r\n";
                String twoHyphens = "--";
                String boundary = "******";
                try {
                    URL url = new URL(uploadUrl);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setUseCaches(false);
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                    httpURLConnection.setRequestProperty("Charset", "UTF-8");
                    httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                    if (key != null && key.length >= 1) {
                        for (int i = 0; i < key.length; i++) {
                            httpURLConnection.setRequestProperty(key[i], value[i]);
                        }

                    }
                    String params = "Content-Disposition: form-data; name=\"" + tag + "\";filename=\"" + tag + end;
                    DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
                    dos.writeBytes(twoHyphens + boundary + end);
                    dos.writeBytes(params);
                    //          dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
                    //                  + uploadFilePath.substring(uploadFilePath.lastIndexOf("/") + 1) + "\"" + end);
                    dos.writeBytes(end);
                    // 文件通过输入流读到Java代码中-++++++++++++++++++++++++++++++`````````````````````````
                    FileInputStream fis = new FileInputStream(uploadFilePath);
                    byte[] buffer = new byte[8192]; // 1kb
                    int count;
                    while ((count = fis.read(buffer)) != -1) {
                        dos.write(buffer, 0, count);
                    }
                    fis.close();
                    System.out.println("file send to server............");
                    dos.writeBytes(end);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
                    dos.flush();

                    // 读取服务器返回结果
                    InputStream is = httpURLConnection.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is, "utf-8");
                    BufferedReader br = new BufferedReader(isr);
                    StringBuilder result = new StringBuilder();
                    String line = br.readLine();
                    while (line != null) {
                        result.append(line);
                        line = br.readLine();
                    }
                    dos.close();
                    is.close();

                    if (updateListener != null) {
                        updateListener.onSuccess(result.toString());
                    }

                } catch (Exception e) {
                    if (updateListener != null) {
                        updateListener.onFail();
                    }
                    e.printStackTrace();
                }

            }
        }).run();
    }


    public interface UpdateListener {
        void onStart();

        void onSuccess(String result);

        void onFail();
    }
}
